#include "../apue.h"
#include <sys/wait.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>

#define CHILD_NAME "practise_8_7_child"

int main(void)
{
    pid_t pid;
    DIR * dir;
    int dfd;
    char * cwd;
    size_t cwdlen;
    char fdstr[20];

    /*the close-on-exec flag will close if use [open] open dir*/
    //if ((dfd = open("/", O_DIRECTORY)) == -1)
    //    err_sys("open error");

    if ((dir = opendir("/")) == NULL)
        err_sys("opendir error");

    if ((dfd = dirfd(dir)) < 0) {
        err_sys("dirdf error");
    }

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
    {
        if (fcntl(dfd, F_GETFD) == FD_CLOEXEC)
            printf("current close-on-exec flag is open\n");
        else
            printf("current close-on-exec flag is close\n");

        //if close close-on-exec flag
        //if (fcntl(dfd, F_SETFD, 0) < 0)
        //    err_sys("fcntl error");

        cwd = path_alloc(&cwdlen);
        getcwd(cwd, cwdlen);
        strcat(cwd, "/");
        strcat(cwd, CHILD_NAME);

        sprintf(fdstr, "%d", dfd);
        execl(cwd, CHILD_NAME, fdstr, NULL);


        //if (-1 == (dfd = open("/", O_DIRECTORY)))
        //    err_sys("open error");

        //if (-1 == (dfd = fcntl(dfd, F_GETFD)))
        //    err_sys("fcntl error");

        //printf("%-9s", "open");
        //if (dfd & FD_CLOEXEC)
        //    printf("close-on-exec flag is on");
        //else
        //    printf("close-on-exec flag is off");

        //if (-1 == close(dfd))
        //    err_sys("close error");
    }

}
